package controller

import (
	"github.com/gofiber/fiber"
	jsoniter "github.com/json-iterator/go"
	"gowork/shoppingCart/model"
	"strconv"
)

type ShoppingCartController struct {
	Commodity *model.Commodity
}

func (scc *ShoppingCartController)AddShoppingCart(c *fiber.Ctx){

	scc.Commodity = new(model.Commodity)

	commodityListStr := c.FormValue("commodityList")
	var commodityList []*model.Commodity
	jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal([]byte(commodityListStr), &commodityList)

	userIdStr := c.FormValue("userId")
	userId, err := strconv.ParseInt(userIdStr, 10, 64)
	if err != nil{
		c.JSON(fiber.Map{
			"code": 500,
			"data": nil,
			"message": err.Error(),
		})
		return
	}

	res , err := scc.Commodity.AddShoppingCart(commodityList, userId)
	if err != nil{
		c.JSON(fiber.Map{
			"code": 500,
			"data": nil,
			"message": err.Error(),
		})
		return
	}

	c.JSON(fiber.Map{
		"code": "200",
		"data": res,
		"message": "成功",
	})
	return
}

func (scc *ShoppingCartController)QueryUserShoppingCardCache(c *fiber.Ctx){

	scc.Commodity = new(model.Commodity)

	userId := c.FormValue("userId")

	res , err := scc.Commodity.QueryUserShoppingCardCache(userId)
	if err != nil{
		c.JSON(fiber.Map{
			"code": 500,
			"data": nil,
			"message": err.Error(),
		})
		return
	}

	c.JSON(fiber.Map{
		"code": "200",
		"data": res,
		"message": "成功",
	})
	return
}

func (scc *ShoppingCartController)Close(c *fiber.Ctx){

	scc.Commodity = new(model.Commodity)

	commodityTypeListStr := c.FormValue("commodityTypeList")
	var commodityTypeList []*model.CommodityTypeCart
	jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal([]byte(commodityTypeListStr), &commodityTypeList)

	couponListStr := c.FormValue("couponList")
	var couponList []*model.Coupon
	jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal([]byte(couponListStr), &couponList)

	//storeIdStr := c.FormValue("storeId")
	//storeId, err := strconv.ParseInt(storeIdStr, 10, 64)
	//if err != nil{
	//	c.JSON(fiber.Map{
	//		"code": 500,
	//		"data": nil,
	//		"message": err.Error(),
	//	})
	//	return
	//}

	res , err := scc.Commodity.Close(commodityTypeList, couponList)
	if err != nil{
		c.JSON(fiber.Map{
			"code": 500,
			"data": nil,
			"message": err.Error(),
		})
		return
	}

	c.JSON(fiber.Map{
		"code": "200",
		"data": res,
		"message": "成功",
	})
	return
}



















